package com.example.myapplication.utils

import java.text.SimpleDateFormat
import java.util.*
import kotlin.random.Random

/**
 * 交易时间辅助类
 * 处理A股交易时间相关逻辑
 */
object TradingTimeHelper {
    
    // A股交易时间段
    private const val MORNING_START = 9 * 60 + 30  // 09:30
    private const val MORNING_END = 11 * 60 + 30   // 11:30
    private const val AFTERNOON_START = 13 * 60    // 13:00
    private const val AFTERNOON_END = 15 * 60      // 15:00
    
    /**
     * 判断是否为交易日（简化版，实际应该查询节假日）
     */
    fun isTradingDay(calendar: Calendar): Boolean {
        val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
        // 排除周六周日
        return dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY
    }
    
    /**
     * 判断是否在交易时间段内
     */
    fun isTradingTime(calendar: Calendar): Boolean {
        if (!isTradingDay(calendar)) return false
        
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val totalMinutes = hour * 60 + minute
        
        // 上午交易时间: 09:30-11:30
        // 下午交易时间: 13:00-15:00
        return (totalMinutes in MORNING_START..MORNING_END) ||
               (totalMinutes in AFTERNOON_START..AFTERNOON_END)
    }
    
    /**
     * 获取最近的交易时间
     * 如果当前不是交易时间，返回下一个交易时间点
     */
    fun getNearestTradingTime(timestamp: Long = System.currentTimeMillis()): Long {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timestamp
        
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val totalMinutes = hour * 60 + minute
        
        // 如果是交易时间，直接返回
        if (isTradingTime(calendar)) {
            return timestamp
        }
        
        // 如果是交易日但不在交易时间
        if (isTradingDay(calendar)) {
            when {
                // 早盘前
                totalMinutes < MORNING_START -> {
                    calendar.set(Calendar.HOUR_OF_DAY, 9)
                    calendar.set(Calendar.MINUTE, 30)
                    calendar.set(Calendar.SECOND, 0)
                }
                // 午休时间
                totalMinutes in (MORNING_END + 1) until AFTERNOON_START -> {
                    calendar.set(Calendar.HOUR_OF_DAY, 13)
                    calendar.set(Calendar.MINUTE, 0)
                    calendar.set(Calendar.SECOND, 0)
                }
                // 收盘后，跳到下一个交易日早盘
                totalMinutes > AFTERNOON_END -> {
                    calendar.add(Calendar.DAY_OF_YEAR, 1)
                    // 跳过周末
                    while (!isTradingDay(calendar)) {
                        calendar.add(Calendar.DAY_OF_YEAR, 1)
                    }
                    calendar.set(Calendar.HOUR_OF_DAY, 9)
                    calendar.set(Calendar.MINUTE, 30)
                    calendar.set(Calendar.SECOND, 0)
                }
            }
        } else {
            // 非交易日，跳到下一个交易日早盘
            calendar.add(Calendar.DAY_OF_YEAR, 1)
            while (!isTradingDay(calendar)) {
                calendar.add(Calendar.DAY_OF_YEAR, 1)
            }
            calendar.set(Calendar.HOUR_OF_DAY, 9)
            calendar.set(Calendar.MINUTE, 30)
            calendar.set(Calendar.SECOND, 0)
        }
        
        return calendar.timeInMillis
    }
    
    /**
     * 获取随机交易时间点
     * 在给定日期的交易时间段内随机选择一个时间
     */
    fun getRandomTradingTime(date: Long): Long {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = date
        
        // 确保是交易日
        if (!isTradingDay(calendar)) {
            return getNearestTradingTime(date)
        }
        
        // 随机选择上午或下午
        val isMorning = Random.nextBoolean()
        
        if (isMorning) {
            // 上午时段 09:30-11:30
            val randomMinutes = MORNING_START + Random.nextInt(MORNING_END - MORNING_START)
            calendar.set(Calendar.HOUR_OF_DAY, randomMinutes / 60)
            calendar.set(Calendar.MINUTE, randomMinutes % 60)
        } else {
            // 下午时段 13:00-15:00
            val randomMinutes = AFTERNOON_START + Random.nextInt(AFTERNOON_END - AFTERNOON_START)
            calendar.set(Calendar.HOUR_OF_DAY, randomMinutes / 60)
            calendar.set(Calendar.MINUTE, randomMinutes % 60)
        }
        
        calendar.set(Calendar.SECOND, Random.nextInt(60))
        return calendar.timeInMillis
    }
    
    /**
     * 格式化交易时间
     */
    fun formatTradingTime(timestamp: Long, pattern: String = "yyyy-MM-dd HH:mm:ss"): String {
        val sdf = SimpleDateFormat(pattern, Locale.CHINA)
        return sdf.format(Date(timestamp))
    }
    
    /**
     * 格式化为日期（用于图表X轴）
     */
    fun formatDate(timestamp: Long): String {
        // 使用 Locale.US 和 Asia/Shanghai 时区确保日期格式正确
        val sdf = SimpleDateFormat("MM/dd", Locale.US)
        sdf.timeZone = java.util.TimeZone.getTimeZone("Asia/Shanghai")
        
        val date = Date(timestamp)
        val formatted = sdf.format(date)
        
        // 添加详细调试日志
        val fullDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).apply {
            timeZone = java.util.TimeZone.getTimeZone("Asia/Shanghai")
        }.format(date)
        android.util.Log.d("📅日期格式化", "timestamp=$timestamp -> $fullDate -> 显示=$formatted")
        
        return formatted
    }
    
    /**
     * 格式化为时间（用于详细显示）
     */
    fun formatTime(timestamp: Long): String {
        val sdf = SimpleDateFormat("HH:mm", Locale.CHINA)
        return sdf.format(Date(timestamp))
    }
    
    /**
     * 判断是否为同一天
     */
    fun isSameDay(timestamp1: Long, timestamp2: Long): Boolean {
        val cal1 = Calendar.getInstance().apply { timeInMillis = timestamp1 }
        val cal2 = Calendar.getInstance().apply { timeInMillis = timestamp2 }
        
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
               cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)
    }
}

